<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path" separator-class="el-icon-arrow-right">
        <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{
          item.meta.title
        }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {
      levelList: [],
    }
  },
  watch: {
    $route(route) {
      // if you go to the redirect page, do not update the breadcrumbs
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    },
  },
  created() {
    this.getBreadcrumb()
  },
  computed:{
    ...mapState({
      topbarRouters:(state)=>state.permission.topbarRouters
    })
  },
  methods: {
    getBreadcrumb() {
      // only show routes with meta.title
      this.levelList=[];
      //  获取路由
    let currentRouter=this.topbarRouters.filter(i=>{
      return this.$route.path.includes(i.path)
    });
    if(currentRouter && currentRouter.length>0){
      this.levelList=  this.getCurrentRouter(currentRouter,this.levelList)
      if(this.$route.query.title){
        this.levelList.push({
          meta:{
            title:this.$route.query.title,
          },
          path:this.$route.path
        })
      }  
    }
    },
    //  获取路由列表
    getCurrentRouter(routers,levelList=[]){
      if(routers && routers.length>0){
        routers.forEach(i=>{
          if(!i.children &&  this.$route.path.includes(i.path)){
          levelList.push(i)
          }else{
            this.getCurrentRouter(i.children,levelList)
          }
        })
        return levelList
      }
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim() === 'Index'
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(path)
    },
  },
}
</script>

<style lang="scss" scoped>
.el-breadcrumb__inner a{
  font-size:20px;
}
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color:  #2F343E;
    font-size:20px;
    cursor: text;
  }
}
</style>
